<template>
	<div class="main">
		<el-form ref="ruleFormRef" :inline="true" :model="dataForm"
			class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
			
			<el-form-item label="仓库">
				<el-cascader v-model="warehouseArr" class="w-full"
					:props="warehouseProps" clearable filterable placeholder="请选择仓库"
					@change="addressChange">
					<template #default="{ node, data }">
						<span>{{ data.name }}</span>
					</template>
				</el-cascader>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="useRenderIcon('ri:search-line')" :loading="loading"
					@click="getInitTable">
					搜索
				</el-button>
				<el-button :icon="useRenderIcon(Refresh)" @click="resetForm(ruleFormRef)">
					重置
				</el-button>
			</el-form-item>
		</el-form>

		<div ref="contentRef" class="flex">
			<PureTableBar class="w-full" style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)" title="库存看板列表"
				:columns="dataColumns" @refresh="getInitTable">
				<template v-slot="{ size, dynamicColumns }">
					<pure-table ref="tableRef" align-whole="center" showOverflowTooltip table-layout="auto"
						:loading="loading" adaptive :adaptiveConfig="{ offsetBottom: 108 }" :size="size"
						:data="dataList" :columns="dynamicColumns" :pagination="pagination" :paginationSmall="false" border
						:header-cell-style="{  background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)'
						}" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
						
						<template #entryTime="{ row }">
							<el-date-picker
								v-model="row.entryTime"
								type="datetime"
								placeholder="请选择入库时间"
								format="YYYY-MM-DD hh:mm:ss"
								value-format="YYYY-MM-DD hh:mm:ss"
								style="width: 100%;"
								@change="entryTimeChange(row)"
							/>
						</template>
					</pure-table>
				</template>
			</PureTableBar>
		</div>
	</div>
</template>

<script setup lang="ts">
	import ReCol from "@/components/ReCol";
	import { useRenderIcon } from "@/components/ReIcon/src/hooks";
	import Refresh from "@iconify-icons/ep/refresh";
	import { ref, reactive, onMounted, toRaw } from "vue";
	import type { PaginationProps } from "@pureadmin/table";
	import type { CascaderProps } from 'element-plus'
	import { message } from "@/utils/message";
	import { PureTableBar } from "@/components/RePureTableBar";
	import {
		getWarehouseListApi,
		getWarehouseAreaListApi,
		getWarehouseLocationListApi,
		updateEntryTimeApi
	} from "@/api/warehouseApi";
	import {
		createExtractApi,
		getWarehouseProductListApi,
	} from "@/api/materialApi";

	const ruleFormRef = ref();
	const dataForm = reactive({
		type: null,
		warehouseId: null,
		warehouseAreaId: null,
		warehouseLocationId: null,
		page: 1,
		perPage: 10,
	})
	const warehouseArr = ref([])
	const warehouseProps : CascaderProps = {
		value: 'id',
		label: 'name',
		emitPath: true,
		lazy: true,
		checkStrictly: true,
		lazyLoad(node, resolve) {
			const { level } = node
			if (level === 0) {
				getWarehouseListApi({ page: 1, perPage: 999 }).then((res) => {
					if (res?.code === 200) {
						for (let item of res.result.list) {
							item.id = item.warehouseId
							item.leaf = false
						}
						resolve(res.result.list)
					}
				})
			} else if (level === 1) {
				getWarehouseAreaListApi({ page: 1, perPage: 999, warehouseId: node.value }).then((res) => {
					if (res?.code === 200) {
						for (let item of res.result.list) {
							item.id = item.warehouseAreaId,
								item.leaf = false
						}
						resolve(res.result.list)
					}
				})
			} else if (level === 2) {
				getWarehouseLocationListApi({ page: 1, perPage: 999, warehouseAreaId: node.value }).then((res) => {
					if (res?.code === 200) {
						for (let item of res.result.list) {
							item.id = item.warehouseLocationId
							item.leaf = true
						}
						resolve(res.result.list)
					}
				})
			}
		},
	}
	const addressChange = (e) => {
		if(e) {
			dataForm.warehouseId = e[0]
			if(e.length === 2) {
				dataForm.warehouseAreaId = e[1]
			}
			if(e.length === 3) {
				dataForm.warehouseAreaId = e[1]
				dataForm.warehouseLocationId = e[2]
			}
		}
	}
	const materialInfo = ref({
		number: '--',
		name: '--',
		category: {
			name: '--'
		},
		warehouse: {
			name: '--'
		},
		unit: {
			name: '--'
		},
		remarks: '',
		spec: ''
	})

	const pagination = reactive<PaginationProps>({
		total: 0,
		pageSize: 10,
		currentPage: 1,
		background: true
	});
	const loading = ref(false)
	const dataList = ref([])

	const dataColumns : TableColumnList = [
		// {
		// 	label: "ID",
		// 	prop: "warehouseProductFlowlogId",
		// 	width: 80
		// },
		{
			label: "仓库",
			prop: "warehouseLocation.name",
			formatter: (row : any) => {
				return row.warehouse?.name + '/' + row.warehouseArea?.name + '/' + row.warehouseLocation?.name
			},
			minWidth: 200
		},
		{
			label: "所在料箱",
			prop: "workbinNo",
			minWidth: 100
		},
		{
			label: "物料编码",
			prop: "material.code",
			minWidth: 180
		},
		{
			label: "物料名称",
			prop: "material.name",
			minWidth: 100
		},
		{
			label: "库存数量",
			prop: "number",
			minWidth: 80
		},
		{
			label: "单位",
			prop: "material.unit.name",
			minWidth: 80
		},
		{
			label: "入库时间",
			prop: "entryTime",
			slot: "entryTime",
			minWidth: 220
		},
		{
			label: "批次号",
			prop: "batchNo",
			minWidth: 150
		},
		{
			label: "生产日期",
			prop: "produceDate",
			minWidth: 150
		},
		{
			label: "状态",
			prop: "status",
			minWidth: 150,
			formatter: (row : any) => {
				return row.status === 1?'正常':'异常'
			},
		},
	]

	
	const getRowspan = (key, rowIndex) => {
	  let rowspan = 1; //默认合并1行
	  let curVal = dataList.value[rowIndex][key]; //存储了当前值
	  for (let i = rowIndex + 1; i < dataList.value.length; i++) {
	    if (dataList.value[i][key] === curVal) {
	      rowspan++;
	    } else {
	      break;
	    }
	  }
	  return rowspan;
	}
	const getInitTable = async () => {
		loading.value = true;
		const { result } = await getWarehouseProductListApi(toRaw(dataForm));
		dataList.value = result.list;
		pagination.total = result.total;
		pagination.pageSize = result.perPage * 1;
		pagination.currentPage = result.page * 1;

		setTimeout(() => {
			loading.value = false;
		}, 150);
	}
	const handleSizeChange = (val) => {
		dataForm.page = 1;
		dataForm.perPage = val;
		getInitTable()
	}
	const handleCurrentChange = (val) => {
		dataForm.page = val;
		getInitTable()
	}
	onMounted(() => {
		getInitTable()
	})
	const resetForm = formEl => {
		if (!formEl) return;
		dataForm.type = null;
		dataForm.warehouseId = null;
		dataForm.warehouseAreaId = null;
		dataForm.warehouseLocationId = null;
		formEl.resetFields();
		getInitTable();
	};
	const entryTimeChange = async(e) => {
		const res = await updateEntryTimeApi({warehouseProductId: e.warehouseProductId, entryTime: e.entryTime})
		if(res?.code ===200) {
			message("时间更新成功!", {
			  type: "success"
			});
			getInitTable()
		}
	}
</script>

<style scoped>
	.main-content {
		margin: 10px 10px 0 !important;
	}

	.appendNum {
		cursor: pointer;
	}

	:deep(.el-input-number) {
		width: 100%;
	}
</style>